<template>
  <div class="mod-retailProd">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="barCode"
            :label="$t('product.singleProductBar')+':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.barCode"
              type="text"
              :placeholder="$t('product.singleProductBar')"
            />
          </el-form-item>
          <el-form-item
            prop="name"
            :label="$t('product.itemName')+':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.name"
              type="text"
              :placeholder="$t('product.itemName')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t("product.addNew") }}
        </div>
        <div
          class="default-btn"
          @click="onImportRetailProd()"
        >
          {{ $t("retailProd.import") }}
        </div>
        <div
          class="default-btn"
          @click="onExportRetailProd()"
        >
          {{ $t("formData.export") }}
        </div>
        <div
          :class="[!dataListSelections.length?'disabled-btn':'','default-btn']"
          @click="onDelete()"
        >
          {{ $t('sys.batchDelete') }}
        </div>
      </div>
      <div class="table-con prod-table">
        <el-table
          ref="prodListTableRef"
          v-loading="dataListLoading"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            align="center"
            width="55"
          />
          <el-table-column
            prop="pic"
            :label="$t('retailProd.pic')"
            width="100"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <ImgShow :src="scope.row.pic" />
              </div>
            </template>
          </el-table-column>

          <el-table-column

            prop="barCode"
            :label="$t('retailProd.barCode')"
            width="250"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.barCode || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="name"
            :label="$t('retailProd.name')"
            width="250"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.name || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="spec"
            :label="$t('retailProd.spec')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.spec || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="categoryName"
            :label="$t('retailProd.categoryName')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.categoryName || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="costPrice"
            :label="$t('retailProd.costPrice')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.costPrice || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="stocks"
            :label="$t('retailProd.stocks')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.stocks || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="unit"
            :label="$t('retailProd.unit')"
            min-width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.unit || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="130"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.retailProdId)"
                >
                  {{ $t("temp.modify") }}
                </div>
                <div
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.retailProdId)"
                >
                  {{ $t("text.delBtn") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>

    <AddOrUpdate
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 单品商品导入 -->
    <ProdImport
      v-if="prodImportVisible"
      ref="prodImportRef"
      @refresh-upload="refreshUpload"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, nextTick, onMounted } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import ProdImport from './components/prod-import.vue'

let tempSearchForm = null // 保存上次点击查询的请求条件

const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  barCode: '',
  name: ''
}) // 搜索
const dataListSelections = ref([])
const dataListLoading = ref(false)

const getDataList = (pageParam, newData = false) => {
  dataListLoading.value = true
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/shop/retailProd/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    dataListLoading.value = false
  })
}
onMounted(() => {
  getDataList()
})
// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}

const onDelete = (id) => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.retailProdId
  })
  if (!ids.length) {
    return
  }
  ElMessageBox.confirm(`${$t('sys.makeSure')}${id ? $t('text.delBtn') : $t('sys.batchDelete')}${$t('text.menu')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/shop/retailProd'),
      method: 'delete',
      // data: http.adornData({})
      data: http.adornData(ids, false)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  }).catch(() => { })
}
/**
 * 刷新回调
 */
const refreshChange = () => {
  getDataList(page)
}
const refreshUpload = () => {
  getDataList(page)
}
const onSearch = (newData = false) => {
  getDataList(page, newData)
}
// 多选变化
const onSelectSome = (val) => {
  dataListSelections.value = val
}
/**
 * 导入单品
 */
const prodImportRef = ref(null)
const prodImportVisible = ref(false)
const onImportRetailProd = () => {
  prodImportVisible.value = true
  nextTick(() => {
    prodImportRef.value?.init()
  })
}
/**
 * 导出单品
 */
const onExportRetailProd = () => {
  const params = {
    ...searchForm,
    imgDomain: resourcesUrl
  }
  http({
    url: http.adornUrl('/shop/retailProd/exportRetailProd'),
    method: 'get',
    params: http.adornParams(params),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = '单品信息表.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}
/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const searchFormRef = ref(null)
const onResetSearch = () => {
  searchFormRef.value.resetFields()
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

</script>
